package com.atom.module.mvvm.base

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.databinding.ViewDataBinding

abstract class AbstractBaseActivity<V : ViewDataBinding, VM : AbstractBaseViewModel<*>> :
    AbstractActivity<V, VM>() {

    override fun initData(view: View) {
        super.initData(view)
        viewModel.also { it ->
            it.finishAction.observe(this) {
                finish()
            }

            it.onBackPressedAction.observe(this) {
                onBackPressed()
            }

            it.startActivityAction.observe(this) { pack ->
                val value = pack.value;
                val clz = value[AbstractBaseViewModel.ParameterField.CLASS] as Class<*>
                val bundle = value[AbstractBaseViewModel.ParameterField.BUNDLE] as Bundle?
                startActivity(clz, bundle)
            }
            it.startActivityForResultAction.observe(this) { pack ->
                val value = pack.value;
                val clz = value[AbstractBaseViewModel.ParameterField.CLASS] as Class<*>
                val requestCode = value[AbstractBaseViewModel.ParameterField.REQUEST] as Int
                val bundle = value[AbstractBaseViewModel.ParameterField.BUNDLE] as Bundle?
                startActivityForResult(clz, requestCode, bundle)
            }
        }
    }


    fun startActivity(clz: Class<*>, bundle: Bundle? = null) {
        val intent = Intent(this, clz)
        if (bundle != null) {
            intent.putExtras(bundle)
        }
        startActivity(intent)
    }

    fun startActivityForResult(clz: Class<*>, requestCode: Int, bundle: Bundle? = null) {
        val intent = Intent(this, clz)
        if (bundle != null) {
            intent.putExtras(bundle)
        }
        startActivityForResult(intent, requestCode)
    }

}